package com.yanqu.road.entity.activity.tongbing.data;

import com.yanqu.road.entity.activity.tongbing.CrossTongBingRankSort;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;

public class CrossTongBingRankListModel {

    private Comparator<CrossTongBingRank> rankSort = new CrossTongBingRankSort();

    private LinkedList<CrossTongBingRank> rankList = new LinkedList<>();

    public void rankChange(CrossTongBingRank rank) {
        synchronized (this) {

            boolean change = false;

            boolean find = false;
            for (CrossTongBingRank tmpRank : rankList) {
                // 找到了
                if (Objects.equals(tmpRank.getId(), rank.getId())) {
                    tmpRank.setValue(rank.getValue());
                    tmpRank.setTime(rank.getTime());
                    change = true;
                    find = true;
                    break;
                }
            }

            if (!find) {
                rankList.add(rank);
                change = true;
            }

            if (change) {
                rankSort();
            }

        }
    }

    public LinkedList<CrossTongBingRank> getRankList() {
        return new LinkedList<>(rankList);
    }

    public void setRankList(LinkedList<CrossTongBingRank> rankList) {
        synchronized (this) {
            this.rankList = rankList;
            rankSort();
        }
    }

    /**
     * 排序，记得加锁
     */
    private void rankSort() {
        rankList.sort(rankSort);
    }
}
